﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Homework2
{
    // *******************************
    // Currently testing using this webpage: http://en.wikipedia.org/wiki/Software_requirements
    // *******************************

    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private List<WebNode> _nodes; // Should only ever contain the root node (HTML tag) of the parsed page

        private WebNode Root
        {
            get
            {
                if (_nodes == null || _nodes.Count != 1)
                {
                    return null;
                }
                else
                {
                    return _nodes.First();
                }
            }
        }

        private void ParseButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(WebpageTextBox.Text))
            {
                return;
            }

            MainTreeView.ItemsSource = null; // Clear out the TreeView's data source

            Cursor = Cursors.Wait;
            ParseButton.IsEnabled = 
            QueryButton.IsEnabled = false;

            var task = Task.Factory.StartNew(text =>
                                             {
                                                 // Parse the webpage
                                                 _nodes = PageParser.ParsePage(text.ToString());
                                                 if (_nodes.Count > 0)
                                                 {
                                                     MainTreeView.Dispatcher.Invoke(new Action(() =>
                                                                                               {
                                                                                                   MainTreeView.ItemsSource = _nodes; // Set the TreeView's data source to the new list of WebNodes
                                                                                               }));
                                                 }
                                             }, WebpageTextBox.Text);

            task.ContinueWith(t =>
                              {
                                  Dispatcher.Invoke(new Action(() =>
                                                               {
                                                                   Cursor = Cursors.Arrow;
                                                                   ParseButton.IsEnabled =
                                                                       QueryButton.IsEnabled = true;
                                                                   MainTabControl.SelectedIndex = 0;
                                                               }));
                              });
        }

        private void QueryButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(QueryTextBox.Text))
            {
                return;
            }

            QueryTreeView.ItemsSource = null;

            
            //query 1.....Select x' from x in "url"
            // should return the sub trees in the order from the page
            if (QueryTextBox.Text == "1")
            {
                QueryTreeView.ItemsSource = _nodes.Prime(); //.Head();
                MainTabControl.SelectedIndex = 1;
            }

            //query 2....Select x'! from x in "url"
            //should return the node of the BODY tag from the page
            else if (QueryTextBox.Text == "2")
            {
                QueryTreeView.ItemsSource = _nodes.Prime().Tail();
                MainTabControl.SelectedIndex = 1;
            }

            //query 3...Select x'& from x in "url"
            //should return the HEAD tag from the page
            else if (QueryTextBox.Text == "3")
            {
                QueryTreeView.ItemsSource = _nodes.Prime().Head();
               // QueryTreeView.ItemsSource = _nodes.Hang("Stuff", null, null, null, null, _nodes.Tail().Head());
                MainTabControl.SelectedIndex = 1;
            }

            //query 4...SELECT [x.Tag] FROM x in doc'
            //returns a new tree containing the Tag values for the first subtree of the document
            else if (QueryTextBox.Text == "4")
            {
                var newNodes = new List<WebNode>();

                foreach (var node in _nodes.Prime(true))
                {
                    newNodes.Add(new WebNode(null, null) { Tag = node.Tag });
                }

                var fauxNode = new WebNode(null, null);
                fauxNode.Children.AddRange(newNodes);

                QueryTreeView.ItemsSource = new List<WebNode> { fauxNode };
                MainTabControl.SelectedIndex = 1;
            }
            else // Try the parser
            { 
                Cursor = Cursors.Wait;
                ParseButton.IsEnabled =
                QueryButton.IsEnabled = false;

                var task = Task.Factory.StartNew(text =>
                                                 {
                                                     // Parse the webpage
                                                     var q = new QueryParser();
                                                     try
                                                     {
                                                         var queryNodes = q.Parser(text.ToString(),
                                                                                   new List<WebNode>(_nodes));
                                                         if (queryNodes != null && queryNodes.Count > 0)
                                                         {
                                                             QueryTreeView.Dispatcher.Invoke(new Action(() =>
                                                                                                        {
                                                                                                            QueryTreeView .ItemsSource = queryNodes; // Set the TreeView's data source to the new list of WebNodes
                                                                                                        }));
                                                         }
                                                     }
                                                     catch (Exception ex)
                                                     {
                                                         Console.WriteLine(ex);
                                                     }
                                                 }, QueryTextBox.Text);

                task.ContinueWith(t =>
                                  {
                                      Dispatcher.Invoke(new Action(() =>
                                                                   {
                                                                       Cursor = Cursors.Arrow;
                                                                       ParseButton.IsEnabled =
                                                                           QueryButton.IsEnabled = true;
                                                                       MainTabControl.SelectedIndex = 1;
                                                                   }));
                                  });
            }
            // Testing...should return the node of the HEAD tag from the page (probably BODY if it doesn't have a HEAD tag)
            //QueryTreeView.ItemsSource = _nodes.Prime().Head();
        }
    }
}
